/**
 * Upload common module
 */
/*
 *
 * props中传入editor 组件updateUploaded
 *
 * */

var React = require("react");
var tool = require("../tool");
var consts = require("../consts");
var storage = require("../storage");
var Upload = React.createClass({
    getInitialState: function () {
        return {
            if_maxfile: false
        }
    },
    getInitialProps: function () {
        return {
            type: "",
            prefix: "",
            root: {},
            dialog: {},
            options: {}
        }
    },
    componentWillMount: function () {
        Dropzone.autoDiscover = false;
        Dropzone.options.myAwesomeDropzone = false;

        var defaultOpts = {
            size: 0
        };
        this.opts = $.extend({}, defaultOpts, this.props.options);
        // 计算MB
        this.opts.size = this.opts.size / 1024 / 1024;

        this.form = {
            model: {}
        };
        this.uploadFiles = [];

        var type = this.props.type;
        if (type == consts.WIDGET_TYPE.PICTURE || type == consts.WIDGET_TYPE.ALBUM) {
            this.form.model.pictures = [];
        }

        this.imageTypes = ["image/jpg", "image/jpeg", "image/gif", "image/png"];
    },
    handleOnCancelUpload: function () {
        // 取消文件上传
        this.dropzoneItem.removeAllFiles(true);
    },
    rebuildFileModel: function (response) {
        return {
            md5: response.md5,
            html: response.file_name,
            url: response.medium_image_src,
            width: response.width,
            height: response.height
        }
    },
    rebuildFileObject: function (file) {
        return file.response ? this.rebuildFileModel(JSON.parse(file.response)) : null;
    },
    removeUploadFiles: function (file) {
        this.uploadFiles.splice(this.uploadFiles.indexOf(file), 1);
    },
    handleOnUploadFile: function (result) {
        var root = this.props.root;
        var type = this.props.type;
        var opts = this.opts;

        var model = this.rebuildFileModel(result);
        if (type == consts.WIDGET_TYPE.PICTURE || type == consts.WIDGET_TYPE.ALBUM) {
            this.form.model.pictures.push(model);
        } else {
            this.form.model = model;
        }
    },
    handleOnRemoveFile: function (file) {
        var root = this.props.root;
        var fileObject = this.rebuildFileObject(file);
        if (fileObject) {
            var index = this.form.model.pictures.indexOf(fileObject);
            this.form.model.pictures.splice(index, 1);
        }
    },
    getBuildWidgets: function () {
        var type = this.props.type,
            pictures = this.form.model.pictures,
            result = [], data;
        var carousel = this.props.data || [];
        for (var i in this.form.model.pictures) {
            carousel.push(this.form.model.pictures[i]);
        }
        pictures = carousel;
        var me = this;
        if (type == consts.WIDGET_TYPE.PICTURE) {
            pictures.map(function (picture, index) {
                data = tool.getWidgetButtonByType(type);
                data.url = data.src = picture.url;
                data.initSort = index;//处理同时上传多张图片时，sort相同的情况，标记
                var item = tool.getRebulidWidget(data, picture);

                // 防止对替换的图片组件进行位置混淆
                delete item.offset_x;
                delete item.offset_y;

                result.push(item);
            });
        } else if (type == consts.WIDGET_TYPE.ALBUM) {
            data = tool.getWidgetButtonByType(type);
            data = tool.getRebulidWidget(data, this.form.model);
            if (pictures.length) {
                var defaultPicture = pictures[0],
                    width = defaultPicture.width,
                    height = defaultPicture.height,
                    resize = tool.resize(width, height);
                data.url = data.src = defaultPicture.url;
                data.width = resize.width;
                data.height = resize.height;
                data.action.carousel = pictures;
                result.push(data);
            }
        }
        return result;
    },
    getBuildPageUpload: function () {
        return this.form.model.pictures;
    },
    showFileErrors: function (file, errors) {
        file.previewElement.classList.add("dz-error");
        file.previewElement.querySelector("[data-dz-errormessage]").textContent = errors;
    },
    check_accept: function (file) {
        var names = file.name.split('.'),
            accepts = this.opts.acceptedFiles.split(','), name = names.length > 1 ? names[1] : "";
        if (file.type) {
            if (accepts.indexOf(file.type) > -1) return true;
        } else {
            for (var i = 0; i < accepts.length; i++) {
                var accept = accepts[i];
                if (accept.match(name)) {
                    return true;
                }
            }
        }

        alert(file.type + "'" + $._('Upload the file in the specified format') + "'(" + this.opts.acceptedFiles + ")");

        return false;
    },
    checkfilesize: function (file) {
        var size = file.size;
        var root = this.props.root;
        var dialog = this.props.dialog;
        var uploadFile = this.uploadFiles.length;
        if (size === 0) {
            alert($._("File size can not be 0"));
            this.showFileErrors(file, $._("File size id error"));
            return false;
        } else {
            // 大于1MB
            if (size > 1024 * 1024) {
                // 计算MB
                size = size / (1024 * 1024);

                // 图片文件单独做容量限制
                if ($.inArray(file.type, this.imageTypes) != -1) {
                    if (size >= 10) {
                        // 为0则表示大小不限制
                        if (this.opts.size !== 0) {
                            //10MB
                            var maxSize = this.opts.size / 10;
                            if (size > maxSize) {
                                this.showFileErrors(file, $._("Image size can not more than 10M"));
                                if (uploadFile == 1) dialog.updateUploaded(true);
                                return false;
                            }
                        }
                    }
                    var maxSize = this.opts.size / 10 / 10; //1M
                    if (size > maxSize && root.state.is_logo_md5) {
                        this.showFileErrors(file, $._("Brand image size can not more than 1M"));
                        dialog.updateUploaded(true);
                        return false;
                    }
                    var maxSize = this.opts.size / 2; //5M
                    if (file.type == 'image/gif' && size > maxSize) {
                        if (file.status != 'error') {
                            this.showFileErrors(file, $._('Gif can not be more than 5M'));
                            if (uploadFile == 1) dialog.updateUploaded(true);
                            return false;
                        }
                    }
                } else {
                    if (size > this.opts.size) {
                        alert("'" + $._('Upload size less than') + "'(" + this.opts.size + "MB)'" + $._("dFile") + "'");
                        return false;
                    }
                }
            }
        }
        return true;
    },
    checkoutImgSize: function (file) {//固定尺寸检查
        // var root = this.props.root,state = root.state;
        const state=this.props.editor;
        var dialog = this.props.dialog;
        if (!state.is_page_back && !state.is_floating_screen) return true;
        var width = file.width,
            height = file.height;
        if (state.is_page_back) {
            var field = {
                width: consts.IMGSIZE_PAGE_BACK.width,
                height: consts.IMGSIZE_PAGE_BACK.height
            }
        } else if (state.is_floating_screen) {
            var field = {
                width: consts.IMGSIZE_FLOATING.width,
                height: consts.IMGSIZE_FLOATING.height,
            }
        }

        if ((width >= field.width - 10 && width < field.width + 10) && (height > field.height - 10 && height < field.height + 10)) {

        } else {
            file.previewElement.classList.add("dz-error");
            file.previewElement.querySelector("[data-dz-errormessage]").textContent = '' + field.width + '*' + field.height + '' + $._("dImage") + '';
            dialog.updateUploaded(true);
            return false;
        }
        return true;
    },
    checkoutImgSizeFree: function (file) {//不超过固定尺寸检查
        // var root = this.props.root,state = root.state;
        const state=this.props.editor;
        var dialog = this.props.dialog;
        if (!state.is_h5_shared_url && !state.is_picture_shared_url) return true;
        var width = file.width,
            height = file.height;
        var field;
        if (state.is_h5_shared_url) {
            field = {
                width: consts.IMGSIZE_H5SHARE.width,
                height: consts.IMGSIZE_H5SHARE.height,
            }
        } else if (state.is_picture_shared_url) {
            field = {
                width: consts.IMGSIZE_PICSHARE.width,
                height: consts.IMGSIZE_PICSHARE.height,
            }
        }
        if (width > field.width + 10 || height > field.height + 10) {
            file.previewElement.classList.add("dz-error");
            file.previewElement.querySelector("[data-dz-errormessage]").textContent = '' + $._("Upload less than") + '' + field.width + '*' + field.height + '' + $._("dImage") + '';
            dialog.updateUploaded(true);
            return false;
        }
        return true;
    },
    componentDidMount: function () {
        var self = this;
        var opts = this.opts;
        var dialog = this.props.dialog;
        var prefix = this.props.prefix;
        var root = this.props.root;
        var type = this.props.type;
        var defaultOpts = {
            url: storage.data.CONST.upload_url,
            params: {
                not_need_narrow: true
            },
            addRemoveLinks: true,
            dictRemoveFile: $._("Remove file"),
            dictCancelUpload: $._('Cancle Upload'),
            dictResponseError: $._('server error'),
            dictFileTooSmall: $._("File size is error"),
            dictInvalidFileType: $._("File type is error"),
            maxFilesize: this.opts.size,
            imgType: this.opts.imgType,
            dictFileTooBig: $._("Image size can not more than 10M"),
            dictFileTooBigLogoMd5: $._("Brand image size can not more than 1M"),
            dictFileTooBigGif: $._('Gif can not be more than 5M'),
            init: function () {
                this.on("addedfile", function (file) {
                    if (!self.check_accept(file) || !self.checkfilesize(file)) {
                        return false;
                    }
                    self.uploadFiles.push(file);
                });
                this.on("removedfile", function (file) {
                    var acceptedList = this.getAcceptedFiles();
                    if (!acceptedList.length) {
                        dialog.updateUploaded(true);
                    }
                }.bind(this));
            },
            success: function (file, response, e) {
                if (!self.checkfilesize(file) || !self.checkoutImgSize(file) || !self.checkoutImgSizeFree(file)) {
                    return false;
                }
                file.previewElement.classList.add("dz-success");

                //dialog.updateUploaded();
                self.handleOnUploadFile(response);
                self.removeUploadFiles(file);

                dialog.updateUploaded(false);

                if (opts.maxFiles == 1) self.setState({if_maxfile: true});
                else self.setState({if_maxfile: false});
                if (type === consts.WIDGET_TYPE.MUSIC || type === consts.WIDGET_TYPE.VIDEO) {
                    var param = {
                        md5: response.md5,
                        html: response.file_name,
                        url: response.image_src || ''
                    }
                    dialog.updateUploadAnimation(param);
                }
                return true;
            },
            removedfile: function (file) {
                if (file.status != 'error') self.handleOnRemoveFile(file.xhr);

                var _ref;
                if ((_ref = file.previewElement) != null) {
                    _ref.parentNode.removeChild(file.previewElement);
                }

                self.setState({if_maxfile: false});
                return this._updateMaxFilesReachedClass();
            },
        };

        this.elements = {
            upload: $(this.refs.upload)
        };

        $.extend(true, opts, defaultOpts);

        var selector = "#" + prefix + " .single-dropzone";
        this.dropzoneItem = new Dropzone(selector, opts);
    },
    render: function () {
        var type = this.props.type;
        var innerNode = '';
        var videoInnerNode = '';
        var carousels = this.props.data || [];
        var dialog = this.props.dialog;
        var rStyle = {};
        var click_upload = $._("Drop files here to upload,or click");
        var remove_file = $._("Remove file");
        var upload_audio = $._('click to upload audio');
        if (type === consts.WIDGET_TYPE.MUSIC) {
            var tips = this.props.tips;
            if (tips) {
                innerNode = <div className='animationMusic'>{tips}</div>
            } else {
                innerNode = <div className='animationMusic'>{upload_audio}</div>
            }
        } else if (type === consts.WIDGET_TYPE.VIDEO) {
            var tips = this.props.tips;
            if (tips) {
                videoInnerNode =
                    <div className="render-video" data-video-helper data-action="form.model" data-pause="pause">
                        <video preload="metadata" controls className="video-js vjs-default-skin" src={tips}
                               width='100%'>
                            <source src={tips}/>
                        </video>
                    </div>
                rStyle = {
                    background: 'none'
                }
            }
        }
        var maxFile = this.opts.maxFiles;
        if (this.dropzoneItem) {
            var item = this.dropzoneItem.files.length;
            if (maxFile == 1 && item == 1) {
                rStyle = {
                    visibility: 'hidden',
                    marginLeft: '98px'
                }
            }
        }
        return (
            <div ref="upload" className="single-dropzone dropzone dz-clickable">
                <div className="dz-default dz-message" style={rStyle}>
                    <span>{click_upload}</span>
                    {innerNode}
                    {videoInnerNode}
                </div>
                <div className="carouse-list">
                    {
                        carousels.map(function (carousel, index) {
                            var backStyle = {
                                background: "url(" + carousel.url + ") no-repeat center",
                            };
                            return (
                                <div className="carousel-item" key={index}>
                                    <div className="carousel-item-img" style={backStyle}></div>
                                    <a href="#" className="ca-remove" name={index}
                                       onClick={dialog.handleOnRemoveCarousel}>{remove_file}</a>
                                    <span className='dz-sucess-mark'></span>
                                </div>
                            )
                        })
                    }
                </div>
            </div>
        )
    }
});

module.exports = Upload;
